package com.buzz.activity;

/**
 * Created by Buzz on 2015/7/6.
 */
import android.app.Service;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;

import com.buzz.models.Mp3Info;

/**
 * Created by Buzz on 2015/7/3.
 */
public class MusicPlayService extends Service{
    private static final String TAG = "PlayerService";

    private static ExhibitionActivity exhibitionActivity = new ExhibitionActivity();
    private static MainActivity mainActivity = new MainActivity();
    public static MediaPlayer mediaPlayer = new MediaPlayer(); 	// 媒体播放器对象
    private String path; 				// 音乐文件路径
    private boolean isPause; 			// 暂停状态
    private int current = 0; 			// 记录当前正在播放的音乐
    private static MyReceiver myReceiver;		// 自定义广播接收器
    private int currentTime;			// 当前播放进度
    private int duration;				// 播放长度
    private boolean bstop = true;	//判断是否为暂停
    private boolean isplay = true; //判断是否可以播放
    static IntentFilter intentFilter = null;
    private static Mp3Info mp3Info = new Mp3Info();
    private int playTime = 0;
    private int listpos = 0;
    private int newPlayPos = 0;
    private int playStatus = 0;
    public static final String STOP_MUSIC = "com.buzz.MusicPlay.STOP_MUSIC";
    public static final String PLAY_MUSIC = "com.buzz.MusicPlay.PLAY_MUSIC";
    public static final String START_MUSIC = "com.buzz.MusicPlay.START_MUSIC";
    public static final String PAUSE_MUSIC = "com.buzz.MusicPlay.PAUSE_MUSIC";
    @Override
    public void onCreate() {
        Log.i(TAG, "this is MusicPlayService");
        super.onCreate();
        // mediaPlayer = new MediaPlayer();//实例媒体播放器对象
        //Log.i(TAG,"OK MediaPlayer");
        //设置音乐播放完成时的监听器
        mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                mediaPlayer.stop();
                mediaPlayer.reset();
                exhibitionActivity.isStopMusic = true;
                mainActivity.isStopMusic = true;
                Intent intent = new Intent(ExhibitionActivity.BACKGROUND);
                sendBroadcast(intent);
                //Intent intent1 = new Intent(MainActivity.BACKGROUND);
                //sendBroadcast(intent1);
            }
        });
        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            /*音乐播放错误重置mediaPlayer*/
            public boolean onError(MediaPlayer mp, int what, int extra) {
                // TODO Auto-generated method stub
                mediaPlayer.release();
                mediaPlayer = null;
                return true;
            }
        });

        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            //当MediaPlayer调用prepare()方法时触发该监听器。
            @Override
            public void onPrepared(MediaPlayer mp) {
                try {
                    Log.w(TAG,"onPrepared");
                    mediaPlayer.start();
                }catch (Exception e){
                    Log.w(TAG,"e = "+e);
                }
            }
        });
        myReceiver = new MyReceiver();
        intentFilter = new IntentFilter();
        intentFilter.addAction(STOP_MUSIC);
        intentFilter.addAction(START_MUSIC);
        intentFilter.addAction(PAUSE_MUSIC);
        intentFilter.addAction(PLAY_MUSIC);
        registerReceiver(myReceiver,intentFilter);
    }
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
    public void play(){
        Log.i(TAG,"str3 = ");
        path =mp3Info.getUrl();
       /* if (mediaPlayer == null){
            mediaPlayer = new MediaPlayer();
        }*/
        try {
            mediaPlayer.reset();// 把各项参数恢复到初始状态
            Log.i(TAG,"str1 = "+path);
            mediaPlayer.setDataSource(path);//设置播放路径
            Log.i(TAG,"str2 = "+path);
            mediaPlayer.prepare(); // 进行缓冲
            Log.i(TAG,"str = "+path);
            // bstop = false;
            //listpos = current;
        } catch (Exception e) {
            Log.w(TAG,"play:" + currentTime + " error:" + e/*.getMessage()*/);//此处有异常
        }
    }

    /**
     * 暂停音乐
     */
    private void pause() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            bstop = true;
            isPause = true;
        }
    }
    /**
     * 停止音乐
     */
    private void stop() {
        Log.v(TAG,"this is stop");
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()){
                mediaPlayer.stop();
                mediaPlayer.reset();
            }
        }
    }

    @Override
    public void onDestroy() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
    public class MyReceiver extends BroadcastReceiver {
            @Override
            public void onReceive(Context context, Intent intent) {

                Log.w(TAG,"this is MyReciver");
                String action = intent.getAction();
                if (action.equals(PLAY_MUSIC)){
                    if (isplay){
                        play();
                        isplay = false;
                    }


                }else if (action.equals(PAUSE_MUSIC)){
                    pause();

                }else if (action.equals(START_MUSIC)){
                    mediaPlayer.start();

                }else if (action.equals(STOP_MUSIC)){
                    if (!isplay){
                        stop();
                        isplay = true;
                    }


                }
            }
    }
    /*private void registerHeadsetPlugReceiver() {
        headsetPlugReceiver = new HeadsetPlugReceiver();
        IntentFilter filter = new IntentFilter(GlobalConst.ACTION_HEADSET_PLUG);
        registerReceiver(headsetPlugReceiver, filter);
    }

    //如果拔出耳塞就暂停播放
    public class HeadsetPlugReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub

            if (intent.hasExtra("state")) {
                if (intent.getIntExtra("state", 0) == 0) {
                    Log.i(TAG, "headset not connected");
                    myApp.headSetConnected = false;
                    Intent intent1 = new Intent(STOP_MUSIC);
                    sendBroadcast(intent1);
                    //btnAudio.setBackground(getResources().getDrawable(R.drawable.icon_voice));
                    isStopMusic = true;
                    background();
                } else if (intent.getIntExtra("state", 0) == 1) {
                    Log.i(TAG, "headset connected");
                    myApp.headSetConnected = true;
                }
            }
        }

    }*/
}
